package com.yebxxx.server.controller;


import com.yebxxx.server.pojo.Admin;
import com.yebxxx.server.pojo.AdminLoginParam;
import com.yebxxx.server.pojo.RespBean;
import com.yebxxx.server.service.IAdminService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;

/**
 * 前端输入用户名和密码进入后端使用spring security 自带的 loadUserByuUsername进行身份验证
 * 如果没有查到消息就返回用户名密码错误，如果查到了就返回一个token对象，以后的操作都将带有这个token请求头，可以判断这个张嘉璈是否过期或者是否合法
 *
 */
@Api(tags = "LoginController")
@RestController
public class LoginController {
    @Autowired
    private IAdminService adminService;

    @ApiOperation(value = "登录之后返回Token")
    @PostMapping("/login")
    public RespBean login(@RequestBody AdminLoginParam adminLoginParam, HttpServletRequest request){
        return adminService.login(adminLoginParam.getUsername(),adminLoginParam.getPassword(),adminLoginParam.getCode(),request);
    }
    @ApiOperation(value = "获取用户登录信息")
    @GetMapping("/admin/info")
    public Admin getAdminInfo(Principal principal){
        if(null==principal){
            return  null;
        }
        String username=principal.getName();
       Admin admin=adminService.getAdminByUsername(username);
       admin.setPassword(null);
       admin.setRoles(adminService.getRoles(admin.getId()));
       return  admin;
    }
    @ApiOperation(value = "退出登录")
    @PostMapping("/logout")
    public  RespBean logout(){
        return  RespBean.success("注销成功");
    }
}
